# 用户相关功能：注册、短信、登录、注销
import os
import time
# 验证码
from io import BytesIO

from django.db.models import Q
from django.http import JsonResponse
from django.shortcuts import render, HttpResponse, redirect
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt
from django.views.generic import View

from account.forms.account import RegisterModelForm, SendSmsForm, LoginSMSForm, LoginForm
from account.models import UserInfo
from utils.image_code import check_code
from utils.tencent.cos import create_bucket
from friendship.models import Follow


# token登录验证


class Register(View):

    def get(self, request):
        form = RegisterModelForm()
        return render(request, 'account/register.html', {'form': form})

    def post(self, request):
        form = RegisterModelForm(data=request.POST)
        if form.is_valid():
            # 验证通过，写入数据库（密码要是密文）
            # instance = form.save，在数据库中新增一条数据，并将新增的这条数据赋值给instance

            # 用户表中新建一条数据（注册）
            form.instance.is_active = False
            form.save()  # form.save()自动剔除无效数据
            bucket = "{}-{}-1305441004".format(form.instance.username, str(int(time.time())))
            region = 'ap-guangzhou'
            create_bucket(bucket, region)

            return JsonResponse({'status': True, 'data': '/login/'})

        return JsonResponse({'status': False, 'error': form.errors})


def send_sms(request):
    """ 发送短信 """
    form = SendSmsForm(request, data=request.GET)
    # 只是校验手机号：不能为空、格式是否正确
    if form.is_valid():  # 在使用is_valid之后才会将数据进行验证
        return JsonResponse({'status': True})

    return JsonResponse({'status': False, 'error': form.errors})


def login_sms(request):
    """ 短信登录 """
    if request.method == 'GET':
        form = LoginSMSForm()
        return render(request, 'account/login_sms.html', {'form': form})

    form = LoginSMSForm(request.POST)
    if form.is_valid():
        # 用户输入正确，登录成功
        mobile_phone = form.cleaned_data['mobile_phone']

        # 把用户名写入到session中
        user_object = UserInfo.objects.filter(mobile_phone=mobile_phone).first()
        request.session['user_id'] = user_object.id
        request.session.set_expiry(60 * 60 * 24 * 14)

        return JsonResponse({'status': True, 'data': '/mood/'})

    return JsonResponse({"status": False, 'error': form.errors})


def login(request):
    # 用户名和密码登录
    if request.method == 'GET':
        form = LoginForm(request)
        return render(request, 'account/login.html', {'form': form})

    form = LoginForm(request, data=request.POST)
    if form.is_valid():
        username = form.cleaned_data['username']
        password = form.cleaned_data['password']

        print(username)
        print(password)

        # user_object = models.UserInfo.objects.filter(username=username, password=password).first()
        # (手机=手机 and pwd=pwd) or (邮箱=username and pwd=pwd)
        user_object = UserInfo.objects.filter(Q(email=username) | Q(mobile_phone=username)).filter(password=password, is_active=True).first()

        if user_object:
            # 用户名&密码正确,登录成功
            request.session['user_id'] = user_object.id
            request.session.set_expiry(60 * 60 * 24 * 14)
            return JsonResponse({'status': True, 'data': '/mood/'})
        form.add_error('username', '用户名或者密码错误')

    return JsonResponse({"status": False, 'error': form.errors})


def image_code(request):
    image_object, code = check_code()

    request.session['image_code'] = code  # 把对应图片的code码自动存入session中。
    request.session.set_expiry(60)  # 主动修改session过期时间为60s，session存放数据数据默认两周。

    stream = BytesIO()
    image_object.save(stream, 'png')

    # return HttpResponse('成功')
    return HttpResponse(stream.getvalue())


def logout(request):
    request.session.flush()
    return redirect('mood')

class Profile(View):
    def get(self, request, user_id):
        user_profile = UserInfo.objects.filter(id=user_id).first()
        is_friend = Follow.objects.filter(user=request.universe.user, follow=user_profile, is_friend=True)

        if is_friend or user_profile == request.universe.user:
            return render(request, 'account/profile.html', {'user_profile': user_profile})
        return HttpResponse('404')


@method_decorator(csrf_exempt, name='dispatch')
class UpdataAvatar(View):

    def post(self, request):
        try:
            user = request.universe.user
            blob_file = request.FILES['avatar']
            image_name = self.save_avatar(user, blob_file)
            user.avatar = os.path.join('avatar', str(user.id), image_name)
            user.save()
        except Exception as e:
            print(e)
            to_json_response = {
                'status': False,
                'data': '用户不存在！'
            }

        return JsonResponse({
            'status': True,
            'data': user.avatar.url
        })

    # 定义手动保存图（IIS下User.save()保存失败）
    def save_avatar(self, user, upload_image):
        import os
        import uuid
        from PIL import Image
        from pathlib import Path
        from django.conf import settings
        # 创建与用户名的文件夹
        upload_path = os.path.join(settings.MEDIA_ROOT, 'avatar', str(user.id))
        is_path = Path(upload_path)
        image_type = Image.open(upload_image)
        print('image_type:{}'.format(image_type))
        print('image_type:{}'.format(image_type.format))
        if not is_path.is_dir():
            try:
                os.mkdir(upload_path)
            except:
                print('创建文件夹错误')
                raise
        # 生成一个随机字符串
        uuid_str_name = uuid.uuid4().hex + '.png'
        # 保存图片
        with open(os.path.join(upload_path, uuid_str_name), 'wb+') as file:
            for chunk in upload_image.chunks():
                file.write(chunk)
        return uuid_str_name
